package com.ricervcvcer.goods.controller;


import com.alibaba.fastjson.JSON;
import com.ricervcvcer.common.util.ResultEntity;
import com.ricervcvcer.common.util.RicervcvcerConstant;
import com.ricervcvcer.goods.entity.TbSku;
import com.ricervcvcer.goods.entity.TbStock;
import com.ricervcvcer.goods.mapper.TbStockMapper;
import com.ricervcvcer.goods.service.ITbSkuService;
import com.ricervcvcer.goods.util.EsConst;
import com.ricervcvcer.goods.vo.SkuStockV0;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * <p>
 * sku表,该表表示具体的商品实体,如黑色的 64g的iphone 8 前端控制器
 * </p>
 *
 * @author moge
 * @since 2022-01-06
 */
@RestController
@RequestMapping("/sku")
public class TbSkuController {
    @Autowired
    ITbSkuService tbSkuService;

    @Autowired
    TbStockMapper tbStockMapper;

    @Autowired
    RestHighLevelClient client;

    @GetMapping("id/{id}")
    public ResultEntity selById(@PathVariable Long id){
        // 查询 sku 和库存
        TbSku sku = tbSkuService.getById(id);
        TbStock tbStock = tbStockMapper.selectById(id);

        SkuStockV0 skuStockV0 = new SkuStockV0();
        skuStockV0.setSku(sku);
        skuStockV0.setStock(tbStock);

        return ResultEntity.successWithData(skuStockV0);
    }

    @Transactional
    @ApiOperation("修改sku信息")
    @PostMapping("editSku")
    public  ResultEntity editSku(@RequestBody SkuStockV0 skuStockV0) {
        // 提取数据
        final TbSku sku = skuStockV0.getSku();
        final TbStock stock = skuStockV0.getStock();

        // 修改
        final boolean skuStatus = tbSkuService.updateById(sku);
        final int stockStatus = tbStockMapper.updateById(stock);

        if(!(skuStatus && stockStatus == 1)) {
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        }

        // 修改es
        UpdateRequest updateRequest = new UpdateRequest(EsConst.ES_INDEX_SKU, String.valueOf(sku.getId()));
        updateRequest.timeout("1s");

        updateRequest.doc(JSON.toJSONString(sku), XContentType.JSON);

        try {
            UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        }

        return ResultEntity.successWithoutData();
    }
}
